import { BasicDrawer, useDrawerInner, useDrawer } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { DrgPrAdjLstApi } from "@/api/pharMgmt/drgPrAdjLst";
import { message } from "antd";
import { useTranslation } from "react-i18next";
import { useState, useMemo } from "react";
import GetDrugIdTable from "./getDrugIdTable";

let reload: Function;
let pkId: any;
const index = (props: { register: Fn }) => {
	const [isUpdated, setIsUpdated] = useState(false);
	const { t } = useTranslation();
	const en_vi = "pharMgmt";
	const formSchema: FormSchema[] = [
		{
			label: t(`${en_vi}.drugId`),
			field: "drugId",
			component: "InputSearch",
			componentProps: {
				onSearch: () => openDrawer(true)
			}
		},
		{
			label: t(`${en_vi}.purPrice`),
			field: "purPrice",
			component: "InputNumber"
		},
		{
			label: t(`${en_vi}.salePrice`),
			field: "salePrice",
			component: "InputNumber"
		}
	];
	const getTitle = useMemo(() => {
		return isUpdated ? t("felix_ui.edit") : t("felix_ui.add");
	}, [isUpdated]);
	const [register, { validateFields, setFieldsValue, resetFields, setFieldValue }] = useForm({
		schemas: formSchema,
		labelWidth: 120,
		baseColProps: {
			span: 24
		}
	});
	const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(props.register, data => {
		reload = data.reload;
		pkId = data.record?.pkId;
		resetFields();
		setDrawerProps({ confirmLoading: true });
		setIsUpdated(!!data?.isUpdated);
		setFieldsValue({
			...data.record
		});
		setDrawerProps({ confirmLoading: false });
	});
	const handleSubmit = async () => {
		const formValue = await validateFields();
		let res;
		if (isUpdated) {
			formValue.pkId = pkId;
			res = await DrgPrAdjLstApi.updateDrgPrAdjLst(formValue);
		} else {
			res = await DrgPrAdjLstApi.createDrgPrAdjLst(formValue);
		}
		if (!res) {
			message.error(t("viewComponents.patientInformation.additionFailed"));
			return;
		}
		message.success(t("viewComponents.patientInformation.successfullyAdded"));
		closeDrawer();
		reload();
	};
	const [drawerDetail, { openDrawer }] = useDrawer();
	const setDrugId = (drugId: any) => {
		console.log("drugId", drugId);
		setFieldValue("drugId", drugId);
	};
	return (
		<>
			<BasicDrawer title={getTitle} showFooter={true} {...props} register={registerDrawer} ok={handleSubmit}>
				<BasicForm register={register} labelWrap={true}></BasicForm>
			</BasicDrawer>
			<GetDrugIdTable register={drawerDetail} setDrugId={setDrugId}></GetDrugIdTable>
		</>
	);
};
export default index;
